package com.acme.controller;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.acme.dao.ZipcodeDAO;
import com.acme.dao.security.DBUserDAO;
import com.acme.entity.User;
import com.acme.entity.Zipcode;
import com.acme.entity.security.DBUserDetails;

@Controller
@Transactional
public class LocateDoctor {

	@Autowired
	private DBUserDAO dbUserDAO;

	@Autowired
	private ZipcodeDAO zipDAO;

	@RequestMapping(value = "locatedoctor")
	public ModelAndView locateDoctor(Map<String, Object> model){
		
		Authentication auth = SecurityContextHolder.getContext().getAuthentication();
		String username = SecurityContextHolder.getContext().getAuthentication().getName();

		// If the user is login, get their information from the database
		if (!(auth instanceof AnonymousAuthenticationToken)) {

			User user = dbUserDAO.getUserByUsername(username);

			List<Zipcode> myZip = zipDAO.getZipcodeByZip(user.getZipcode());

			double latitude = myZip.get(0).getLatitude();
			double longitude = myZip.get(0).getLongitude(); 
//			// new york location
//			double latitude = 40.750742;  
//			double longitude = -73.99653;
			
			ModelAndView mav = new ModelAndView("LocateDoctor");
			mav.getModelMap().addAttribute("lat", latitude);
			mav.getModelMap().addAttribute("long", longitude);

			return mav; 
		} else {								// Default Location to davenport, IA
			// Davenport IA location
			double latitude = 41.5431;
			double longitude = -90.5908;

			ModelAndView mav = new ModelAndView("LocateDoctor");
			mav.getModelMap().addAttribute("lat", latitude);
			mav.getModelMap().addAttribute("long", longitude);
			
			return mav;
		}
	}
}
